(function(window, angular, document) {


	function config($stateProvider, $urlRouterProvider, TabsProvider) {
		var defaultState = 'index';
		TabsProvider
			.setDefaultState(defaultState)
			.pushTab(defaultState, '基本信息')
			.pushTab('buy', '买水订单')
			// .pushTab('recharge', '充值订单')
			.setTabRouter($stateProvider, $urlRouterProvider);
	}

	function TabsProvider() {
		var tabs = {};
		var activeTab = null;
		var defaultState = null;

		var CLASS_ON = 'on';
		var CLASS_OFF = 'off';

		function Tab(state, title) {
			this.state = state;
			this.class = CLASS_OFF;
			this.title = title;
		}
		Tab.prototype.go = function() {
			if (activeTab) {
				activeTab.class = CLASS_OFF;
			}
			this.class = CLASS_ON;
			activeTab = this;
		}

		this.setDefaultState = function(state) {
			defaultState = state;
			return this;
		}

		this.pushTab = function(state, title) {
			tabs[state] = new Tab(state, title);
			return this;
		}
		this.setTabRouter = function($stateProvider, $urlRouterProvider) {
			for (var state in tabs) {
				var url = '/' + state;
				var tpl = state + '.html';
				var ctrl = state + 'Ctrl';
				var cfg = {
					url: url,
					templateUrl: tpl,
					controller: ctrl,
				};
				$stateProvider.state(state, cfg);
			}
			if (defaultState) {
				$urlRouterProvider.otherwise(defaultState);
			}
		}
		this.$get = function() {
			return {
				getTabs: function() {
					return tabs;
				},
				activeTab: function(state) {
					if (tabs[state]) {
						tabs[state].go();
					}
				}
			};
		}
	}

	function tabCtrl($scope, $state, $timeout, Tabs) {
		$scope.tabs = Tabs.getTabs();
		$scope.go = function(tab) {
			$state.go(tab.state);
			tab.go();
		}

		$timeout(function() {
			if (window.location.hash) {
				var activeState = window.location.hash.replace(/#\/(\w+)/, '$1');
				if ($scope.tabs[activeState]) {
					$scope.tabs[activeState].go();
				}
			}
		}, 200);

	}

	function indexCtrl($scope, $uibModal, User, School) {
		var user = $scope.user = User;
		$scope.schoolList = School.fetchSchoolList();
		var updateData = $scope.updateData = {};
		updateDataInit();

		function updateDataInit() {
			$scope.updateData = updateData = {
				schoolID: User.school.id
			};
		}
		// 处理用户模型的更新后续操作
		function handleUpdate(promise, successMsg, failMsg) {
			var successMsg = successMsg || '修改成功';
			var failMsg = failMsg || '修改失败';

			promise.then(function() {
				alert(successMsg);
			}).catch(function() {
				alert(failMsg);
				location.reload();
				// updateDataInit();
			})
		}
		// 设为"普通用户"/"测试人员"
		$scope.setTester = function(isTester) {
			var role = user.isTest ? '普通用户' : '调试人员';
			var msg = '确定将['+user.nickname+']设为['+role+']';
			if( confirm(msg) ){
				handleUpdate(User.setTester(isTester));
			}
		};
		// 修改学校
		$scope.update = function() {
			handleUpdate(User.update(updateData));
		};
		// 清空余额
		$scope.emptyBalance = function() {
			if (confirm('确定清空用户[' + user.nickname + ']的余额,共' + (user.balance / 100) + '元?')) {
				handleUpdate(User.emptyBalance(), '清除用户余额成功', '清除用户余额失败');
			}
		};
		// 赠送水费
		$scope.presrentBalance = function() {
			var modal = $uibModal.open({
				templateUrl: 'presrentBalance.html',
				controller: 'presrentBalanceModalCtrl',
			});
			modal.result.then(function(data) {
				handleUpdate(User.presrentBalance(data.amount, data.reason),'赠送成功','赠送失败');
			});

		};
		// 解绑离线授权手机
		$scope.unbindOfflinePhone = function() {
			if(confirm('解绑后,会将预付款余额转移到用户可用余额,确定?')){
				handleUpdate(User.unbindOfflinePhone(),'解绑成功','解绑失败');
			}
		};
	}

	function UserFactory($rootScope, $q, School, API) {
		var user = {
			balance: 0,
			rechargeTotal: 0,
			buyTotal: 0,
			presrent: 0,
			prepayment: 0,
			nickname: '',
			isTest: 0,
			lockedPhoneID:0,
			isBindWechat:0,
			isBindOfflinePhone:0,
		};
		setData(window.app.config.user);

		function setData(data) {
			for (var key in data) {
				set(key, data[key]);
			}
		}

		function set(key, val) {
			switch (key) {
				case 'balance':
				case 'rechargeTotal':
				case 'buyTotal':
				case 'presrent':
				case 'prepayment':
					user[key] = parseInt(val);
					break;
				case 'isTest':
					user.isTest = parseInt(val);
					break;
				case 'schoolID':
					user.school = School.getSchoolById(val);
					break;
				case 'isBindOfflinePhone':
				case 'lockedPhoneID':
					user.isBindOfflinePhone = !!val;
					// user.lockedPhoneID = val;
					break;
				case 'isBindWechat':
				case 'wxOpenID':
					user.isBindWechat = !!val;
					break;
				default:
					user[key] = val;
					break;
			}
		}

		function fetch(url, params, successCallback) {
			var defer = $q.defer();
			API.fetch(url, params).then(function(rtn) {
				if (rtn.result) {
					if (successCallback instanceof Function) {
						successCallback(rtn);
					}
					defer.resolve();
				} else {
					defer.reject();
				}
			}).catch(function() {
				defer.reject();
			});
			return defer.promise;
		}

		user.setTester = function(isTester) {
			var url = 'set_tester';
			var params = {
				'uid': this.id,
				'isTester': Number(!this.isTest),
			}
			return fetch(url, params, function() {
				set('isTest', params.isTester);
			})
		};
		user.update = function(params) {
			var url = 'update';
			params.uid = this.id;
			return fetch(url, params, function(rtn) {
				set('schoolID', params.schoolID);
			});
		};
		user.emptyBalance = function() {
			var url = 'empty_balance';
			var params = {
				uid: user.id,
			}
			return fetch(url, params, function() {
				user.balance = 0;
			});
		}
		user.presrentBalance = function(amount, reason) {
			var amount = parseInt(amount);
			var url = 'presrent';
			var params = {
				uid: user.id,
				amount: amount,
				reason: reason,
			}
			return fetch(url, params, function() {
				user.balance += amount;
				user.presrent += amount;
			});
		}
		user.unbindOfflinePhone = function() {
			var url = 'unbind_offline_phone';
			var params = {
				uid : user.id
			}
			return fetch(url,params,function(){
				user.balance+=user.prepayment;
				user.prepayment = 0;
				user.isBindOfflinePhone = false;
			})
		}


		return user;
	}

	function buyOrdersFactory(API, CFG, User) {
		function load() {
			var url = CFG.adminDir + 'buy/user_order';
			var params = {
				uid: User.id,
			}
			return API.fetch(url, params);
		}

		function closeOrder(orderID) {
			var url = CFG.adminDir + 'buy/close_order';
			var params = {
				uid: User.id,
				orderID: orderID,
			}
			return API.fetch(url, params);
		}
		return {
			load: load,
			closeOrder: closeOrder,
		}
	}

	function buyCtrl($scope, buyOrders) {
		buyOrders.load().then(function(rtn) {
			if (!rtn.list)
				return false;
			$scope.buyOrderRows = rtn.list;
		});

		$scope.closeOrder = function(order) {
			buyOrders.closeOrder(order.id).then(function() {
				alert('关闭订单成功');
				order.isFinish = 1;
			});
		}
	}

	function rechargeCtrl($scope) {
		$scope.title = '充值订单';
	}

	function presrentBalanceModalCtrl($scope, $uibModalInstance, User) {
		var data = $scope.data = {
			amount: 0,
			reason: '',
		};
		$scope.user = User;
		$scope.cancel = function() {
			//dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
			$uibModalInstance.dismiss('cancel');
		}
		$scope.confirm = function() {
			if (data.amount <= 0) {
				alert('请填写正确的赠送金额');
				return false;
			}
			if (data.reason.length > 50) {
				alert('赠送理由不得超过15个字');
				return false;
			}
			//close函数是在模态框关闭后调用的函数,他会将这个参数传到主控制器的results函数中,作为回调值
			$uibModalInstance.close(data);
		}
	}

	var module = angular.module('UserDetailModule', ['Common', 'Ys', 'ui.router', 'ngAnimate', 'ui.bootstrap']);
	module.config(['$stateProvider', '$urlRouterProvider', 'TabsProvider', config]);
	module.provider('Tabs', TabsProvider);
	module.controller('tabCtrl', tabCtrl);
	module.factory('User', UserFactory);
	module.factory('buyOrders', buyOrdersFactory);
	module.controller('indexCtrl', indexCtrl);
	module.controller('buyCtrl', buyCtrl);
	module.controller('rechargeCtrl', rechargeCtrl);
	module.controller('presrentBalanceModalCtrl', presrentBalanceModalCtrl);

})(window, angular, document)